﻿using Newtonsoft.Json;
using QunProject.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace QunProject.Web.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// 换成实例
        /// </summary>
        public Cache.ICache Cache = QunProject.Cache.ExampleCache.GetExampleCache();

        /// <summary>
        /// 返回数据对象
        /// </summary>
        public Common.Result Result = new Common.Result();

        /// <summary>
        /// 用户token
        /// </summary>
        public string token
        {
            get
            {
                var token = Common.HttpHelper.GetCookieValue("ASP_NET_TOKEN");
                return token;
            }
            set
            {
                Common.HttpHelper.SetCookie("ASP_NET_TOKEN", value);
            }
        }

        /// <summary>
        /// 获取登录用户
        /// </summary>
        public Model.member LoginMember
        {
            get
            {
                Model.member _member = null;
                if (!token.IsNullOrWhiteSpace())
                {
                    if (Cache.Get(token) != null)
                    {
                        _member = (Model.member)Cache.Get(token);
                    }
                    else
                    {
                        Common.Result result = UserLoginInfoResult();
                        if (result.succ)
                        {
                            _member = JsonConvert.DeserializeObject<Model.member>(JsonConvert.SerializeObject(result.data));
                            Cache.Set(token, _member, 120);
                        }
                        else
                        {
                            token = null;
                        }
                    }
                }
                return _member;
            }
            set
            {
                if (value == null)
                {
                    if (!token.IsNullOrWhiteSpace())
                    {
                        Cache.Clear(token);
                        Common.HttpHelper.ClearCookie("ASP_NET_TOKEN");
                    }
                }
            }
        }

        /// <summary>
        /// 刷新用户信息
        /// </summary>
        public void RefreshLoginMember()
        {
            Model.member _member = null;
            if (!token.IsNullOrWhiteSpace())
            {
                Common.Result result = UserLoginInfoResult();
                if (result.succ)
                {
                    _member = JsonConvert.DeserializeObject<Model.member>(JsonConvert.SerializeObject(result.data));
                    Cache.Set(token, _member, 120);
                }
                else
                {
                    token = null;
                }
            }
        }

        /// <summary>
        /// Api地址
        /// </summary>
        public readonly string ApiUrl = ConfigurationManager.AppSettings["ApiUrl"];

        /// <summary>
        /// DomainUrl地址
        /// </summary>
        public readonly string DomainUrl = ConfigurationManager.AppSettings["DomainUrl"];

        /// <summary>
        /// ManageUrl地址
        /// </summary>
        public readonly string ManageUrl = ConfigurationManager.AppSettings["ManageUrl"];

        /// <summary>
        /// 网页附加后缀
        /// </summary>
        public readonly string Suffix = ConfigurationManager.AppSettings["Suffix"];

        /// <summary>
        /// HttpPost请求数据
        /// </summary>
        /// <param name="name">接口名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public string HttpPost(string name, string data = "")
        {
            return Common.HttpHelper.HttpPost($"{ApiUrl}/{name}?token={token}", data);
        }

        /// <summary>
        /// HttpPost请求数据
        /// </summary>
        /// <param name="name">接口名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public string HttpPost(string name, Dictionary<string, string> data)
        {
            var paras = JsonConvert.SerializeObject(data);
            return Common.HttpHelper.HttpPost($"{ApiUrl}/{name}?token={token}", paras);
        }

        /// <summary>
        /// HttpGet请求数据
        /// </summary>
        /// <param name="name">接口名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public string HttpGet(string name, string data = "")
        {
            return Common.HttpHelper.HttpGet($"{ApiUrl}/{name}?token={token}", data);
        }

        /// <summary>
        /// HttpPost请求数据
        /// </summary>
        /// <param name="name">接口名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public string HttpGet(string name, Dictionary<string, string> data)
        {
            var paras = JsonConvert.SerializeObject(data);
            return Common.HttpHelper.HttpGet($"{ApiUrl}/{name}?token={token}", paras);
        }

        /// <summary>
        /// 获取组合对象值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="methodName">方法名</param>
        /// <returns></returns>
        public System.Collections.Generic.Dictionary<string, string> WeaveParameters<T>(string methodName) where T : new()
        {
            Type type = typeof(T);
            List<string> paraNames = new List<string>();
            foreach (var method in type.GetMethods())
            {
                if (method.Name == methodName)
                {
                    foreach (var para in method.GetParameters())
                    {
                        paraNames.Add(para.Name);
                    }
                    break;
                }
            }
            System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
            foreach (var para in paraNames)
            {
                dic.Add(para, Request[para]);
            }
            return dic;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="code">验证码</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public Common.Result SendSmsResult(string phone, string code, int type = (int)Model.EnumHelper.SmsType.其他)
        {
            var paras = new Dictionary<string, string>();
            paras.Add("phone", phone);
            paras.Add("code", code);
            paras.Add("type", type.ToString());
            return JsonConvert.DeserializeObject<Common.Result>(HttpPost("SendSmsResult", paras));
        }

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <returns></returns>
        public Result UserLoginInfoResult()
        {
            return JsonConvert.DeserializeObject<Common.Result>(HttpPost("UserLoginInfoResult"));
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="type">上传类型枚举</param>
        /// <param name="base64">base64字符串</param>
        /// <returns></returns>
        public JsonResult FileUpload(int type = (int)FileHelper.FileTypes.不限制, string base64 = "")
        {
            base64 = base64.Replace("+", "[a]");
            base64 = base64.Replace("=", "[e]");
            var paras = new { type, base64 };
            var result = HttpPost("FileUpload", JsonConvert.SerializeObject(paras));
            return Json(result);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public JsonResult WangEditorUpload()
        {
            var files = Request.Files;
            if (files.Count <= 0)
                return Json("error|请选择上传的文件");


            List<string> imgList = new List<string>();

            //相对路径
            string relativePath = $"/Upload/WangEditor/{DateTime.Now.ToString("yyyy/MM/dd/")}";
            //绝对路径
            string absolutePath = Server.MapPath(relativePath);
            if (!Directory.Exists(absolutePath))
                Directory.CreateDirectory(absolutePath);

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];
                //源文件名
                string sourceFileName = file.FileName;
                //文件后缀名
                string fileExtension = sourceFileName.Substring(sourceFileName.LastIndexOf('.'), sourceFileName.Length - sourceFileName.LastIndexOf('.'));
                //新文件名
                string currentFileName = Guid.NewGuid().ToString("N") + fileExtension;
                //文件保存路径
                string imagePath = absolutePath + currentFileName;
                //保存文件相对路径
                var path = relativePath + currentFileName;
                //保存文件
                file.SaveAs(imagePath);
                //获取图片url地址
                string imgUrl = DomainUrl + path;
                imgList.Add(imgUrl);
            }

            var data = new { errno = 0, data = imgList };
            return Json(data);
        }

        /// <summary>
        /// 进入方法前
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string controllers = filterContext.RouteData.Values["controller"].ToString().ToLower();
            if (controllers == "member")
            {
                if (LoginMember == null)
                {
                    filterContext.RequestContext.HttpContext.Response.Redirect("/login/index?type=loginout");
                }
            }
            ViewBag.ManageUrl = ManageUrl;
            ViewBag.FileApiUrl = ApiUrl;
            ViewBag.Suffix = Suffix;
            ViewBag.LoginMember = LoginMember;
            ViewBag.Keywords = "CoderTalking,NET社区,代码分享,技术分享";
            ViewBag.Description = "CoderTalking（www.codertalking.com）是一个程序员的技术分享社区，专为程序员提供讨论交流的地方，也可以在这里分享自己的技术和经验，和每一个人共同学习共同进步";
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 发生错误时
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            if (Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.Clear();
                Common.Result result = new Result();
                filterContext.HttpContext.Response.Write(result.Fail("发生了错误"));
            }
            else
            {
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.Redirect($"/Home/Error{Suffix}");
            }
            base.OnException(filterContext);
        }
    }
}